/**
 * Copyright (C) 2009-2012, KingHool.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses.
 */
package com.kinghool.smodel.io.source;


import com.kinghool.smodel.IModel;
import com.kinghool.smodel.def.ModelDefinition;
import com.kinghool.smodel.io.IModelChannel;
import com.kinghool.smodel.io.IModelSource;

/**
 * 
 * @Author Allen Deng(dengtailin@gmail.com) 
 */
public abstract class BaseModelSource<E extends IModel> implements IModelSource<E> {
	
	protected IModelChannel channel;
	 
	protected abstract E newModelInstance(ModelDefinition modelDefinition);

	public BaseModelSource(IModelChannel modelMapAccessor) {
		this.channel = modelMapAccessor;
	}  
 
	public E load() {
		return load(getModelDefinition(String.valueOf(channel.getRootId())));
	}
	
	public E load(ModelDefinition modelDefinition) {
		if (modelDefinition == null) {
			modelDefinition = getModelDefinition(String.valueOf(channel.getRootId()));
		}
		E model = newModelInstance(modelDefinition);
		channel.loadModel(model);
		return model;
	} 

	public void flush(E model) {
		channel.flushModel(model);
	}

	public void setModelMapChannel(IModelChannel channel) {
		this.channel = channel;
	}	  
	
	protected abstract ModelDefinition getModelDefinition(String id);
}
